<!-- templates/suppliers/list.html -->
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>供货商管理 - 商店进销存管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 阿里云 CDN -->
    <link href="https://unpkg.com/element-plus@2.4.3/dist/index.min.css" rel="stylesheet">
    <script src="https://unpkg.com/element-plus@2.4.3/dist/index.full.min.js"></script>

    <!-- 引入 Toastify CSS 和 JS -->
    <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.js"></script>

    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .sidebar-item {
                @apply flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-all duration-200;
            }

            .sidebar-item.active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }

            .card-shadow {
                @apply shadow-md hover:shadow-lg transition-shadow duration-300;
            }
        }
    </style>
</head>

<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-cubes text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-gray-800">商店进销存管理系统</h1>
        </div>

        <div class="flex items-center space-x-6">
            <div class="relative">
                <input type="text" placeholder="搜索..."
                       class="pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>

            <div class="flex items-center space-x-4">
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-bell-o text-xl"></i>
                </button>
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-cog text-xl"></i>
                </button>
                <div class="flex items-center space-x-2 cursor-pointer">
                    <img src="https://picsum.photos/200/200" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
                    <span class="text-gray-700">管理员</span>
                </div>
            </div>
        </div>
    </div>
</header>

<div class="flex flex-1 overflow-hidden">
    <!-- 侧边栏导航 -->
    <aside class="w-64 bg-white shadow-md h-[calc(100vh-64px)] overflow-y-auto transition-all duration-300">
        <nav class="py-4">
            <div class="px-4 mb-4">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">主菜单</h2>
            </div>

            <a href="../../index.html" class="sidebar-item" data-path="../../index.html">
                <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
                <span>仪表盘</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">基础信息</h2>
            </div>

            <a href="productlist.html" class="sidebar-item" data-path="productlist.html">
                <i class="fa fa-shopping-bag w-5 h-5 mr-3"></i>
                <span>商品管理</span>
            </a>

            <a href="categorylist.html" class="sidebar-item" data-path="categorylist.html">
                <i class="fa fa-th-large w-5 h-5 mr-3"></i>
                <span>类别管理</span>
            </a>

            <a href="supplierlist.html" class="sidebar-item active" data-path="supplierlist.html">
                <i class="fa fa-truck w-5 h-5 mr-3"></i>
                <span>供货商管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">库存管理</h2>
            </div>

            <a href="warehouselist.html" class="sidebar-item" data-path="warehouselist.html">
                <i class="fa fa-archive w-5 h-5 mr-3"></i>
                <span>仓库管理</span>
            </a>

            <a href="inventorylist.html" class="sidebar-item" data-path="inventorylist.html">
                <i class="fa fa-list-alt w-5 h-5 mr-3"></i>
                <span>库存查询</span>
            </a>

            <a href="instock.html" class="sidebar-item" data-path="instock.html">
                <i class="fa fa-sign-in w-5 h-5 mr-3"></i>
                <span>入库管理</span>
            </a>

            <a href="outstock.html" class="sidebar-item " data-path="outstock.html">
                <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
                <span>出库管理</span>
            </a>

            <a href="transfer.html" class="sidebar-item" data-path="transfer.html">
                <i class="fa fa-exchange w-5 h-5 mr-3"></i>
                <span>转仓管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">统计分析</h2>
            </div>

            <a href="../../statistics/sales.html" class="sidebar-item">
                <i class="fa fa-line-chart w-5 h-5 mr-3"></i>
                <span>销售统计</span>
            </a>

            <a href="../../statistics/inventory.html" class="sidebar-item">
                <i class="fa fa-pie-chart w-5 h-5 mr-3"></i>
                <span>库存分析</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">系统设置</h2>
            </div>

            <a href="salesman.html" class="sidebar-item" data-path="salesman.html">
                <i class="fa fa-user-circle w-5 h-5 mr-3"></i>
                <span>用户管理</span>
            </a>


            <a href="backup.html" class="sidebar-item" data-path="system/logs.html">
                <i class="fa fa-history w-5 h-5 mr-3"></i>
                <span>数据库备份与恢复</span>
            </a>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="flex-1 overflow-y-auto bg-gray-50 p-6">
        <div class="container mx-auto">
            <!-- 页面标题 -->
            <div class="mb-6">
                <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">供货商管理</h2>
                <p class="text-gray-500 mt-1">管理商店的所有供货商信息</p>
            </div>

            <!-- 操作按钮 -->
            <div class="mb-4 flex justify-between items-center">
                <button class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center" id="addSupplierBtn">
                    <i class="fa fa-plus mr-2"></i> 添加供货商
                </button>
            </div>

            <!-- 筛选表单 -->
            <div class="mb-4 bg-white rounded-lg p-4 card-shadow">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">供货商名称</label>
                        <input type="text" id="filterName" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入供货商名称">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">联系人</label>
                        <input type="text" id="filterContact" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入联系人姓名">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">联系电话</label>
                        <input type="text" id="filterPhone" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入联系电话">
                    </div>
                    <div class="flex items-end space-x-2">
                        <button id="filterBtn" class="flex-1 bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center justify-center">
                            <i class="fa fa-filter mr-2"></i> 筛选
                        </button>
                        <button id="resetFilterBtn" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
                            重置
                        </button>
                    </div>
                </div>
            </div>

            <!-- 供货商列表 -->
            <div class="bg-white rounded-xl p-6 card-shadow">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                        <tr class="border-b border-gray-200">
                            <th class="py-3 text-left text-sm font-medium text-gray-500">供货商编号</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">供货商名称</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">联系人</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">联系电话</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">地址</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">状态</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">操作</th>
                        </tr>
                        </thead>
                        <tbody id="supplierTable">
                        <!-- 数据将通过JS动态渲染 -->
                        </tbody>
                    </table>
                </div>

                <!-- 分页控件 -->
                <div class="mt-6 flex justify-between items-center">
                    <div class="text-sm text-gray-500" id="paginationInfo">共 0 条记录</div>
                    <div class="flex space-x-1" id="paginationControls">
                        <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 disabled:opacity-50" disabled>
                            <i class="fa fa-chevron-left"></i>
                        </button>
                        <button class="px-3 py-1 border border-primary bg-primary text-white rounded-md">1</button>
                        <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">2</button>
                        <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">3</button>
                        <button class="px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50">
                            <i class="fa fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 页脚 -->
<footer class="bg-white py-4 border-t border-gray-200">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>© 2025 商店进销存管理系统 - 版权所有</p>
    </div>
</footer>

<!-- 供货商添加模态框 -->
<div id="supplierModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>
<!-- 编辑供货商模态框 -->
<div id="editSupplierModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>
<!-- JavaScript -->
<script>
    // 权限检查函数
    function hasPermission(permissionCode) {
        // 从localStorage或cookie中获取用户权限列表
        const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]');
        return userPermissions.includes(permissionCode);
    }

    // 根据角色隐藏/展示按钮
    const applyRolePermissions = () => {
        fetch('/user-info')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`获取用户信息失败: 状态码 ${response.status}`);
                }
                return response.json(); // 解析JSON格式响应
            })
            .then(data => {
                console.log('用户信息响应:', data);

                // 检查响应结构是否正确
                if (data.code !== "200" || !data.data) {
                    throw new Error(data.message || '响应数据格式错误');
                }

                const userData = data.data;
                const authorities = userData.authorities;

                // 使用正则表达式提取角色信息（假设authorities格式为"Roles:[ROLE_USER]"）
                const roles = authorities.match(/Roles:\[(.*?)\]/);
                if (roles) {
                    const roleList = roles[1].split(","); // 注意：后端返回的是ROLE_USER，无空格，使用逗号直接分割
                    console.log('用户角色:', roleList);

                    // 存储用户权限到localStorage
                    localStorage.setItem('userPermissions', JSON.stringify(roleList));

                    if (!roleList.includes("ROLE_ADMIN")) {
                        // 隐藏管理员专属按钮
                        const addSupplierBtn = document.getElementById('addSupplierBtn');
                        if (addSupplierBtn) {
                            addSupplierBtn.style.display = 'none';
                        }

                        // 隐藏需要管理员权限的按钮
                        document.querySelectorAll('[data-permission]').forEach(button => {
                            const requiredPermission = button.getAttribute('data-permission');
                            if (!hasPermission(requiredPermission)) {
                                button.style.display = 'none';
                            }
                        });
                    }
                } else {
                    console.warn('未找到角色信息，原始数据:', authorities);
                }
            })
            .catch(error => {
                console.error('获取用户信息失败:', error);
                Toastify({
                    text: '获取用户权限失败，请重新登录',
                    duration: 3000,
                    gravity: 'top',
                    position: 'right',
                    backgroundColor: '#f44336'
                }).showToast();
            });
    };

    // 确保在商品数据加载完成后再次应用权限
    const ensurePermissionsApplied = () => {
        // 如果数据是异步加载的，可能需要在数据加载完成后再次调用
        setTimeout(() => {
            applyRolePermissions();
        }, 500); // 等待500毫秒，确保数据加载完成
    };
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        initSidebarNavigation();
        setCurrentPageActive();
        loadSuppliers(); // 加载供货商数据

        // 应用角色权限
        applyRolePermissions();

        // 确保数据加载完成后再次应用权限
        ensurePermissionsApplied();

        // 筛选按钮点击事件
        document.getElementById('filterBtn').addEventListener('click', applyFilter);

        // 重置筛选按钮点击事件
        document.getElementById('resetFilterBtn').addEventListener('click', resetFilter);

        // 绑定添加供货商按钮事件
        document.getElementById('addSupplierBtn').addEventListener('click', showAddSupplierForm);

        // 绑定编辑商品按钮事件
        document.addEventListener('click', (e) => {
            // 处理编辑按钮
            if (e.target.closest('.edit-btn')) {
                const button = e.target.closest('.edit-btn');
                const supplierId = parseInt(button.getAttribute('data-id'));
                editSupplier(supplierId);
            }

            // 处理删除按钮
            if (e.target.closest('.delete-btn')) {
                const button = e.target.closest('.delete-btn');
                const supplierId = parseInt(button.getAttribute('data-id'));
                deleteSupplier(supplierId);
            }
        });
    });

    // 全局筛选参数
    let filterParams = {
        name: '',
        contact: '',
        phone: ''
    };

    /**
     * 应用筛选条件
     */
    const applyFilter = () => {
        // 获取筛选表单的值
        filterParams = {
            name: document.getElementById('filterName').value.trim(),
            contact: document.getElementById('filterContact').value.trim(),
            phone: document.getElementById('filterPhone').value.trim()
        };

        // 从第一页开始加载数据
        loadSuppliers(0);
    };

    /**
     * 重置筛选条件
     */
    const resetFilter = () => {
        // 重置表单
        document.getElementById('filterName').value = '';
        document.getElementById('filterContact').value = '';
        document.getElementById('filterPhone').
        document.getElementById('filterName').value = '';
        document.getElementById('filterContact').value = '';
        document.getElementById('filterPhone').value = '';

        // 重置筛选参数
        filterParams = {
            name: '',
            contact: '',
            phone: ''
        };

        // 从第一页开始加载数据
        loadSuppliers(0);
    };

    /**
     * 从后端API加载供货商数据（支持筛选）
     */
    let currentPage = 0; // 保存当前页码（后端从0开始）
    const loadSuppliers = (page = 0) => {
        const supplierTable = document.getElementById('supplierTable');
        const paginationInfo = document.getElementById('paginationInfo');
        const paginationControls = document.getElementById('paginationControls');

        // 显示加载中状态
        supplierTable.innerHTML = `
    <tr>
      <td colspan="7" class="py-4 text-center">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        <p class="mt-2 text-gray-600">加载供货商数据中...</p>
      </td>
    </tr>
  `;

        // 构建筛选参数
        const queryParams = new URLSearchParams({
            page: page,
            size: 10,
            ...(filterParams.name && { name: filterParams.name }),
            ...(filterParams.contact && { contact: filterParams.contact }),
            ...(filterParams.phone && { phone: filterParams.phone })
        });

        // 调用后端API获取供货商数据
        fetch(`/supplier?${queryParams}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('API响应数据:', apiResponse);
                supplierTable.innerHTML = '';

                // 验证响应结构
                if (!apiResponse || apiResponse.code !== "200" || !apiResponse.data) {
                    throw new Error(apiResponse?.message || 'API响应失败');
                }

                // 解构数据
                const { content: suppliers, totalElements, totalPages, pageable } = apiResponse.data;
                const currentPage = pageable.pageNumber; // 后端从0开始，前端从1开始

                // 更新分页信息
                const displayPage = currentPage + 1;
                paginationInfo.textContent = `共 ${totalElements} 条记录，当前第 ${displayPage} 页`;
                updatePaginationControls(totalPages, displayPage);

                // 处理无数据情况
                if (suppliers.length === 0) {
                    supplierTable.innerHTML = `
          <tr>
            <td colspan="7" class="py-4 text-center text-gray-500">没有找到符合条件的供货商数据</td>
          </tr>
        `;
                    return;
                }

                // 过滤有效数据
                const validSuppliers = suppliers.filter(supplier =>
                    supplier && typeof supplier === 'object' && supplier.supplierId !== undefined
                );

                if (validSuppliers.length === 0) {
                    throw new Error('所有供货商数据均无效');
                }

                // 渲染供货商数据
                validSuppliers.forEach(supplier => {
                    const row = document.createElement('tr');
                    row.className = 'border-b border-gray-100 hover:bg-gray-50';

                    // 从API数据中提取字段（含默认值处理）
                    const id = supplier.supplierId;
                    const name = supplier.supplierName || '未知名称';
                    const contact = supplier.contactPerson || '无';
                    const phone = supplier.contactPhone || '无';
                    const address = supplier.address || '无';
                    const status = supplier.status || 'active';

                    // 状态显示转换
                    const statusText = status === 'active' ?
                        '<span class="px-2 py-1 text-xs rounded-full bg-success/10 text-success">合作中</span>' :
                        '<span class="px-2 py-1 text-xs rounded-full bg-gray-100 text-gray-500">已停用</span>';

                    row.innerHTML = `
          <td class="py-3 text-sm text-gray-600">${id}</td>
          <td class="py-3 text-sm text-gray-600">${name}</td>
          <td class="py-3 text-sm text-gray-600">${contact}</td>
          <td class="py-3 text-sm text-gray-600">${phone}</td>
          <td class="py-3 text-sm text-gray-600">${address}</td>
          <td class="py-3 text-sm text-gray-600">${statusText}</td>
          <td class="py-3 text-sm text-gray-600">
            <button data-id="${id}" class="edit-btn text-primary mr-2" data-permission="SUPPLIER_EDIT">
              <i class="fa fa-pencil"></i> 编辑
            </button>
            <button data-id="${id}" class="delete-btn text-danger" data-permission="SUPPLIER_DELETE">
              <i class="fa fa-trash"></i> 删除
            </button>
          </td>
        `;
                    supplierTable.appendChild(row);
                });
            })
            .catch(error => {
                console.error('加载供货商数据失败:', error);
                supplierTable.innerHTML = `
        <tr>
          <td colspan="7" class="py-4 text-center text-red-500">
            <i class="fa fa-exclamation-circle mr-2"></i> 加载供货商数据失败，请稍后重试
          </td>
        </tr>
      `;

                Toastify({
                    text: `加载供货商数据失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };

    /**
     * 更新分页控件
     */
    const updatePaginationControls = (totalPages, currentPage) => {
        const controls = document.getElementById('paginationControls');
        controls.innerHTML = '';

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
        prevBtn.disabled = currentPage === 1;
        prevBtn.innerHTML = '<i class="fa fa-chevron-left"></i>';
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                loadSuppliers(currentPage - 2); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(prevBtn);

        // 页码按钮 (显示当前页及前后两页)
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `px-3 py-1 border rounded-md text-gray-700 hover:bg-gray-50 ${i === currentPage ? 'border-primary bg-primary text-white' : ''}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', () => {
                loadSuppliers(i - 1); // 转换为后端页码（前端页码-1）
            });
            controls.appendChild(pageBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.innerHTML = '<i class="fa fa-chevron-right"></i>';
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                loadSuppliers(currentPage); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(nextBtn);
    };

    /**
     * 显示添加供货商表单
     */
    const showAddSupplierForm = () => {
        const modal = document.getElementById('supplierModal');
        modal.classList.remove('hidden');

        const formContainer = document.createElement('div');
        formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
        formContainer.innerHTML = `
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-xl font-semibold text-gray-800">添加新供货商</h3>
      <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('supplierModal').classList.add('hidden')">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <form id="addSupplierForm" class="space-y-4">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="supplierName">供货商名称</label>
        <input type="text" id="supplierName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="contactPerson">联系人</label>
        <input type="text" id="contactPerson" name="contactPerson" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="contactPhone">联系电话</label>
        <input type="tel" id="contactPhone" name="contactPhone" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="address">地址</label>
        <textarea id="address" name="address" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"></textarea>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="description">备注</label>
        <textarea id="description" name="description" rows="2" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"></textarea>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="status">状态</label>
        <select id="status" name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
          <option value="active">合作中</option>
          <option value="inactive">已停用</option>
        </select>
      </div>
      <div class="flex justify-end space-x-3 mt-6">
        <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('supplierModal').classList.add('hidden')">取消</button>
        <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">添加供货商</button>
      </div>
    </form>
  `;

        modal.innerHTML = '';
        modal.appendChild(formContainer);

        // 表单提交事件
        document.getElementById('addSupplierForm').addEventListener('submit', (e) => {
            e.preventDefault();
            addSupplier();
        });
    };

    /**
     * 添加供货商到系统
     */
    const addSupplier = () => {
        // 获取表单数据
        const formData = {
            supplierName: document.getElementById('supplierName').value,
            contactPerson: document.getElementById('contactPerson').value,
            contactPhone: document.getElementById('contactPhone').value,
            address: document.getElementById('address').value,
            description: document.getElementById('description').value,
            status: document.getElementById('status').value
        };

        // 显示加载状态
        const submitButton = document.querySelector('#addSupplierForm button[type="submit"]');
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 提交中...';

        // 调用API
        fetch('/supplier', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('添加供货商API响应:', apiResponse);

                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '添加供货商';

                // 处理响应
                if (apiResponse) {
                    Toastify({
                        text: "供货商添加成功",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();
                    // 关闭表单
                    document.getElementById('supplierModal').classList.add('hidden');
                    // 刷新供货商列表
                    loadSuppliers();
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '添加失败：未知错误';
                    alert(errorMsg);
                }
            })
            .catch(error => {
                console.error('添加供货商失败:', error);
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '添加供货商';
                // 显示错误信息
                alert('添加供货商失败: ' + error.message);
            });
    };

    /**
     * 加载供货商详情
     */
    const fetchSupplierDetails = async (supplierId) => {
        try {
            const response = await fetch(`/supplier/${supplierId}`);
            if (!response.ok) {
                throw new Error(`获取供货商详情失败: 状态码 ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('获取供货商详情失败:', error);
            Toastify({
                text: `获取供货商详情失败: ${error.message}`,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            throw error;
        }
    };

    /**
     * 显示编辑供货商表单
     */
    const showEditSupplierForm = (supplierId) => {
        const modal = document.getElementById('editSupplierModal');
        modal.classList.remove('hidden');

        const formContainer = document.createElement('div');
        formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
        formContainer.innerHTML = `
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-xl font-semibold text-gray-800">编辑供货商</h3>
      <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('editSupplierModal').classList.add('hidden')">
        <i class="fa fa-times"></i>
      </button>
    </div>
    <form id="editSupplierForm" class="space-y-4">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editSupplierName">供货商名称</label>
        <input type="text" id="editSupplierName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editContactPerson">联系人</label>
        <input type="text" id="editContactPerson" name="contactPerson" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editContactPhone">联系电话</label>
        <input type="tel" id="editContactPhone" name="contactPhone" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editAddress">地址</label>
        <textarea id="editAddress" name="address" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"></textarea>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editDescription">备注</label>
        <textarea id="editDescription" name="description" rows="2" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"></textarea>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1" for="editStatus">状态</label>
        <select id="editStatus" name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
          <option value="active">合作中</option>
          <option value="inactive">已停用</option>
        </select>
      </div>
      <div class="flex justify-end space-x-3 mt-6">
        <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('editSupplierModal').classList.add('hidden')">取消</button>
        <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">保存修改</button>
      </div>
    </form>
  `;

        modal.innerHTML = '';
        modal.appendChild(formContainer);

        // 加载供货商详情并填充表单
        fetchSupplierDetails(supplierId)
            .then(supplier => {
                document.getElementById('editSupplierName').value = supplier.supplierName || '';
                document.getElementById('editContactPerson').value = supplier.contactPerson || '';
                document.getElementById('editContactPhone').value = supplier.contactPhone || '';
                document.getElementById('editAddress').value = supplier.address || '';
                document.getElementById('editDescription').value = supplier.description || '';
                document.getElementById('editStatus').value = supplier.status || 'active';
            })
            .catch(() => {
                // 加载失败时清空表单
                document.getElementById('editSupplierName').value = '';
                document.getElementById('editContactPerson').value = '';
                document.getElementById('editContactPhone').value = '';
                document.getElementById('editAddress').value = '';
                document.getElementById('editDescription').value = '';
                document.getElementById('editStatus').value = 'active';
            });

        // 表单提交事件
        document.getElementById('editSupplierForm').addEventListener('submit', (e) => {
            e.preventDefault();
            updateSupplier();
        });
    };

    /**
     * 更新供货商信息
     */
    const updateSupplier = () => {
        if (!currentEditingSupplierId) {
            Toastify({
                text: "编辑失败：未选择供货商",
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            return;
        }

        // 获取表单数据
        const formData = {
            supplierId: currentEditingSupplierId,
            supplierName: document.getElementById('editSupplierName').value,
            contactPerson: document.getElementById('editContactPerson').value,
            contactPhone: document.getElementById('editContactPhone').value,
            address: document.getElementById('editAddress').value,
            description: document.getElementById('editDescription').value,
            status: document.getElementById('editStatus').value
        };

        // 显示加载状态
        const submitButton = document.querySelector('#editSupplierForm button[type="submit"]');
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';

        // 调用API
        fetch(`/supplier/${formData.supplierId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('更新供货商API响应:', apiResponse);

                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '保存修改';

                // 处理响应
                if (apiResponse) {
                    Toastify({
                        text: "供货商更新成功",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();
                    // 关闭表单
                    document.getElementById('editSupplierModal').classList.add('hidden');
                    // 刷新供货商列表
                    loadSuppliers();
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '更新失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();
                }
            })
            .catch(error => {
                console.error('更新供货商失败:', error);
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '保存修改';
                // 显示错误信息
                Toastify({
                    text: `更新供货商失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };

    /**
     * 编辑供货商
     */
    let currentEditingSupplierId = null;
    const editSupplier = (supplierId) => {
        currentEditingSupplierId = supplierId;
        showEditSupplierForm(supplierId);
    };

    /**
     * 删除供货商
     */
    const deleteSupplier = (supplierId) => {
        if (confirm('确定要删除这个供货商吗？此操作不可恢复。')) {
            // 找到触发事件的按钮
            const deleteBtn = event?.target?.closest('button') ||
                document.querySelector(`button[onclick="deleteSupplier(${supplierId})"]`);

            if (deleteBtn) {
                deleteBtn.disabled = true;
                deleteBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 处理中...';
            }

            fetch(`/supplier/${supplierId}`, {
                method: 'DELETE'
            })
                .then(response => {
                    if (response.ok) {
                        Toastify({
                            text: "供货商删除成功",
                            duration: 3000,
                            gravity: "top",
                            position: "right",
                            backgroundColor: "#4CAF50",
                        }).showToast();

                        loadSuppliers();
                    } else {
                        throw new Error(`删除失败: ${response.statusText}`);
                    }
                })
                .catch(error => {
                    console.error('删除供货商失败:', error);
                    Toastify({
                        text: `供货商删除失败: ${error.message}`,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();
                })
                .finally(() => {
                    if (deleteBtn) {
                        deleteBtn.disabled = false;
                        deleteBtn.innerHTML = '<i class="fa fa-trash"></i> 删除';
                    }
                });
        }
    };

    /**
     * 初始化侧边栏导航
     */
    const initSidebarNavigation = () => {
        const sidebarItems = document.querySelectorAll('.sidebar-item');

        sidebarItems.forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();

                const path = item.getAttribute('data-path');
                if (!path) return;

                // 更新激活状态
                updateActiveItem(item);

                // 显示加载指示器
                showPageLoader();

                // 使用平滑过渡加载新页面
                setTimeout(() => {
                    window.location.href = path;
                }, 300); // 动画持续时间
            });
        });
    };

    /**
     * 更新激活菜单项
     */
    const updateActiveItem = (activeItem) => {
        document.querySelectorAll('.sidebar-item').forEach(item => {
            item.classList.remove('active');
        });
        activeItem.classList.add('active');
    };

    /**
     * 设置当前页面菜单项为激活状态
     */
    const setCurrentPageActive = () => {
        const currentPath = window.location.pathname;
        const sidebarItems = document.querySelectorAll('.sidebar-item');

        sidebarItems.forEach(item => {
            const itemPath = item.getAttribute('data-path');
            if (itemPath && currentPath.endsWith(itemPath)) {
                updateActiveItem(item);
                return;
            }
        });
    };

    /**
     * 显示页面加载指示器
     */
    const showPageLoader = () => {
        const mainContent = document.querySelector('main');

        // 创建加载指示器元素
        const loader = document.createElement('div');
        loader.className = 'fixed inset-0 bg-white bg-opacity-80 flex items-center justify-center z-50 transition-opacity duration-300';
        loader.innerHTML = `
        <div class="text-center">
          <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
          <p class="mt-4 text-gray-600">加载中...</p>
        </div>
      `;

        // 添加到页面
        document.body.appendChild(loader);

        // 300ms后移除（与导航延迟匹配）
        setTimeout(() => {
            loader.classList.add('opacity-0');
            setTimeout(() => {
                document.body.removeChild(loader);
            }, 300);
        }, 300);
    };
</script>
</body>

</html>